package com.u.social.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.u.social.article.entity.ArticleComments;
import com.u.social.article.entity.ArticleStats;
import com.u.social.article.mapper.ArticleCommentsMapper;
import com.u.social.article.model.CommentDTO;
import com.u.social.article.model.converter.CommentConverter;
import com.u.social.article.service.IArticleCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.u.social.article.service.IArticleStatsService;
import com.u.social.article.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-02-24
 */
@Service
public class ArticleCommentsServiceImpl extends ServiceImpl<ArticleCommentsMapper, ArticleComments> implements IArticleCommentsService {


    @Autowired
    private CommentConverter commentConverter;

    @Autowired
    private IRedisService redisService;

    @Autowired
    private IArticleStatsService articleStatsService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveComment(CommentDTO commentDTO){
        ArticleComments articleComments = commentConverter.toArticleComments(commentDTO);
        this.save(articleComments);

        String articleId = articleComments.getArticleId().toString();
        redisService.incrementHash("article_comment_count", articleId, 1);
        return true;
    }

    /**
     * 定时任务，每隔1分钟执行一次，同步点赞状态到数据库
     */
    @Scheduled(fixedRate = 1000 * 60) // 每隔1分钟执行一次
    public void syncLikeStatus() {
        // 1. 批量同步评论数量到数据库
        List<ArticleStats> articleStatsList = new ArrayList<>();
        redisService.getAllHash("article_comment_count").forEach((k, v) -> {
            Long articleId = Long.parseLong(k.toString());
            Integer commentCount = Integer.parseInt(v.toString());

            ArticleStats articleStats  = articleStatsService.getOne(new QueryWrapper<ArticleStats>().eq("article_id", articleId));
            if(articleStats == null) {
                articleStats = new ArticleStats();
            }

            articleStats.setCommentCount(commentCount);
            articleStatsList.add(articleStats);
        });

        if(!articleStatsList.isEmpty()){
            articleStatsService.saveOrUpdateBatch(articleStatsList);
        }
    }


}
